acessos = {["tela_grupos"] = 5, ["tela_mataMata1"] = 5, ["tela_mataMata2"] = 5}
filename = "../user_preferences"

function file_exists()
	file, err = io.open(filename, "r")

	if (err ~= nil) then
		print('[t-cup]: Creating new user preferences file...')

		file = io.open(filename, "w")
		file:write("tela_grupos=0\n")
		file:write("tela_mataMata1=0\n")
		file:write("tela_mataMata2=0\n")
		file:close()

		return false
	end

	file:close()

	return true
end

function loadscreen()
	print('[t-cup]: Loading first screen')

	local tela = "tela_principal"
	local valorAtual = 0
	if (file_exists()) then
		for line in io.open(filename):lines() do
			print ("[t-cup]: line=" .. line)
			key, value = string.match(line, "^([a-zA-Z0-9_]*)%=([0-9]*)$")
			--print ("[t-cup]: key=" .. key .. " value=".. value)
			if (tonumber(value) > acessos[key] and tonumber(value) > valorAtual) then
				tela = key
				valorAtual = tonumber(value)
				break
			end
		end
	end
	event.post('out', {class = 'ncl', type = 'presentation', action = 'start', label = tela})
end

function handler(evt)
	print('[t-cup]: Entering on handler function')

	--print('[t-cup]: User preferences file: '..filename)

	if evt.class ~= 'ncl' then return end
    if (evt.type == 'presentation' and evt.action == 'start') then
		loadscreen()
	elseif (evt.type == 'attribution') and (evt.name == 'tela') and
		(file_exists()) then
		print('[t-cup]: Updating user preferences')
		tela = evt.value
		local aa = ""
		local muda = 0
		file = io.open(filename, "r")
		for line in file:lines() do
			key, value = string.match(line, "^([a-zA-Z0-9_]*)%=([0-9]*)$")
			if (key == tela) then
				aa = aa .. key .. "=" .. (value + 1) .. "\n"
				muda = 1
			else
				aa = aa .. line .. "\n"
			end
		end
		file:close()
		if (muda == 1) then
			file = io.open(filename, "w")
			file:write(aa)
			file:flush()
			file:close()
		end
    end
    print('[t-cup]: Leaving handler function')
    event.post {
        class  = 'ncl',
        type   = 'attribution',
        name   = 'tela',
        action = 'stop',
        value  = evt.value,
    }
end

event.register(handler)